/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.AccountObject;

public class AuthenticationFilter implements Filter {
	AccountInformationDatastore d = new AccountInformationDatastore();

	private FilterConfig fc; 
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		boolean authorized = false;
		if (req instanceof HttpServletRequest) {
			HttpServletRequest httpreq = (HttpServletRequest) req;
			Cookie[] cookies = httpreq.getCookies();
			String user = null;
			String auth = null;
			if (cookies != null) {
				for (int i = 0; i < cookies.length; i++) {
					if (cookies[i].getName().equals("user"))
						user = cookies[i].getValue();
					if (cookies[i].getName().equals("auth"))
						auth = cookies[i].getValue();
				}

				if (user != null && auth != null) {
					AccountObject ao = d.getAccountObject(user);
					if (ao.getAuthkey().equals(auth) && ao.isActivated())
						authorized = true;
				}
			}
		}
		if (authorized) {
	        chain.doFilter(req, resp);
	        return;
	    } else if (req.getContentType() != null && req.getContentType().contains("text/xml")){
	    	resp.setContentType("text/xml");
	    	resp.getWriter().write("<error>Get outta here</error>");
	    }
	    else {
	    	fc.getServletContext().getRequestDispatcher("/debug.jsp?msg=unauthorized").forward(req, resp);
	    }

	}

	@Override
	public void destroy() {
		this.fc = null;
	}

	@Override
	public void init(FilterConfig fc) throws ServletException {
		this.fc = fc;
	}
}
